<?php
/**
 * 商品管理
 * Created by PhpStorm.
 * User: qinzhi
 * Date: 2017/07/03
 * Time: 20:19
 */
class Controller_Adminmall_Goods extends Controller_Adminmall_Abstract
{


    private $DB_SERVER = "xhs_slave";
    private $DB_SERVER_MASTER = "xhs_master";

    public function listAction(){
//        $this->openDebug();
        $title = FRequest::getString('title');
        $page = FRequest::getInt("page");
        $is_banner = FRequest::getInt("is_banner");
        $goodsection = FRequest::getInt("goodsection");
        $is_soldout = FRequest::getInt("is_soldout");
        $status = FRequest::getInt("status");


        $where = array();


        if($title){
            $where['title'] = array('like' => "%{$title}%");
        }
        if($is_banner){
            $where['is_banner'] =$is_banner;
        }
        if($goodsection){
            $where['goodsection'] =$goodsection;
        }
        if($is_soldout){
            $where['is_soldout'] = $is_soldout;
        }
        if($status){
            $where['status'] = $status;
        }else{
            $where['status'] = array("neq" => -1);
        }

        $table = new FTable("goods", "", $this->DB_SERVER);

        $list = $table->fields("*")
            ->where($where)
            ->order("paixu desc")
            ->limit(20)
            ->page($page)
            ->select();
        $pagerInfo = $table->getPagerInfo();
        $this->assign('page_info', $pagerInfo);
        $this->assign("data", $list);

        $cateTable = new FTable("goods_category", '', $this->DB_SERVER);
        $cateList = $cateTable->select();
        $this->assign("goodsectionList", $cateList);
        $img_oss = FConfig::get("global.s_url_oss");
        $this->assign('img_oss', $img_oss);
        $this->display("goods/goods-list");
    }


    public function goodsModifyAction(){

        global $_F;
//        $this->openDebug();
        if ($this->isPost()){
            $id = FRequest::getPostInt('id');
            $title = FRequest::getPostString('title');
            $freight = FRequest::getPostString('freight');
            $cs_num = FRequest::getPostInt('cs_num');
            $paynum = FRequest::getPostInt('paynum');
            $is_banner = FRequest::getPostInt('is_banner');
            $goodsection = FRequest::getPostInt('goodsection');
            $num = FRequest::getPostInt('num');
            $brand = FRequest::getPostString('brand');
            $lefttext = FRequest::getPostString('lefttext');
            $resume = FRequest::getPostString('resume');
            $details = FRequest::getPostString('details');
            $place_of_production = FRequest::getPostString('place_of_production');
            $quality_guarantee_period = FRequest::getPostString('quality_guarantee_period');
            $component = FRequest::getPostString('component');
            $paixu = FRequest::getPostInt('paixu');
            $status = FRequest::getPostInt('status');
            $saveData = array(
                "title" => $title,
                "mid" => $_F['uid'],
                "freight" => $freight,
                "cs_num" => $cs_num,
                "paynum" => $paynum,
                "is_banner" => $is_banner,
                "goodsection" => $goodsection,
                "num" => $num,
                "brand" => $brand,
                "lefttext" => $lefttext,
                "resume" => $resume,
                "details" => $details,
                "place_of_production" => $place_of_production,
                "quality_guarantee_period" => $quality_guarantee_period,
                "component" => $component,
                "paixu" => $paixu,
                "status" => $status,
            );


            if (!empty($_FILES["img2"]['name'])) {
                $img2_url = Service_Attach::getInstance()->uploadOSS('img2','wx/picwx','jpg');
                $saveData['img2'] = $img2_url;
            }else{
                $saveData['img2'] = $_POST['img2'];
            }

            if (!empty($_FILES["img3"]['name'])) {
                $img2_url = Service_Attach::getInstance()->uploadOSS('img2','wx/picwx','jpg');
                $saveData['img3'] = $img2_url;
            }else{
                $saveData['img3'] = $_POST['img3'];
            }



            $table = new FTable("goods","",'xhs_master');
            if ($id) {
                $table->update($saveData, array('auto_id' => $id));
                return $this->success('商品修改成功。', $_F['refer']);
            } else {
                $ret = $table->insert($saveData);
                return $this->success('商品增加成功。', $_F['refer']);
            }



        }

        $table = new FTable("goods","",$this->DB_SERVER);
        $id=FRequest::getInt('id');
        if($id){
            $data = $table->fields("*")
                ->where(array('auto_id' => $id))
                ->find();
//            var_dump($data);
            $this->assign('data', $data);
        }

        $cateTable = new FTable("goods_category", '', $this->DB_SERVER);
        $cateList = $cateTable->select();
        $this->assign("goodsectionList", $cateList);

        $goodsStatus = FConfig::get("type.goodsStatus");
        $this->assign("goodsStatus", $goodsStatus);
        $img_oss = FConfig::get("global.s_url_oss");
        $this->assign('img_oss', $img_oss);
        $this->display("goods/goods-modify");
    }

    public function addAction(){
        global $_F;

        if($this->isPost()){
            $this->openDebug();
//            echo json_encode($_POST);exit;
            $title = FRequest::getPostString('title'); //标题
            $resume = FRequest::getPostString('resume'); //简述
            $status = FRequest::getPostInt('status'); //状态
            $_spec_list = $_POST['_spec_list']; //属性列表
            $_num = $_POST['_num']; //库存
            $_price_old = $_POST['_price_old']; //原价
            $_price_new = $_POST['_price_new']; //现价
            $_purchase_price = $_POST['_purchase_price']; //成本价
            $_profit = $_POST['_profit']; //利润
            $_weight = $_POST['_weight']; //重量
            $_default = intval($_POST['_default']); //默认
            $unit = $_POST['unit']; //单位
            $details = $_POST['details'] ? $_POST['details'] : ""; //详情
            $mid = $_F['uid']; //管理员ID

            $freight = FRequest::getPostString('freight');
            $cs_num = FRequest::getPostInt('cs_num');
            $paynum = FRequest::getPostInt('paynum');
            $is_banner = FRequest::getPostInt('is_banner');
            $goodsection = FRequest::getPostInt('goodsection');
            $brand = FRequest::getPostString('brand');
            $lefttext = FRequest::getPostString('lefttext');
            $place_of_production = FRequest::getPostString('place_of_production');
            $quality_guarantee_period = FRequest::getPostString('quality_guarantee_period');
            $component = FRequest::getPostString('component');
            $paixu = FRequest::getPostInt('paixu');
            $re_degree = FRequest::getPostInt('re_degree');

            $total_num = array_sum($_num);
            $goods = array(
                'title' => $title,
                'mid' => $mid,
                'resume' => $resume,
                'status' => $status,
                'unit' => $unit,
                'purchase_price' => $_purchase_price[$_default]?$_purchase_price[$_default]:0,
                'price_old' => $_price_old[$_default],
                'price_new' => $_price_new[$_default],
                'profit' => $_profit[$_default]?$_profit[$_default]:0,
                'weight' => $_weight[$_default]?$_weight[$_default]:0,
                'num' => $total_num?$total_num:0,
                'details' => $details,
                'create_time' => date('Y-m-d H:i:s'),
                'freight' => $freight?$freight:0,
                'cs_num' => $cs_num?$cs_num:0,
                'paynum' => $paynum?$paynum:0,
                'is_banner' => $is_banner,
                'goodsection' => $goodsection,
                'brand' => $brand,
                'lefttext' => $lefttext,
                'place_of_production' => $place_of_production,
                'quality_guarantee_period' => $quality_guarantee_period,
                'component' => $component,
                'paixu' => $paixu,
                're_degree' => $re_degree,
            );

            //封面图片和列表图片
            $img1 = "";
            if (!empty($_FILES["img2"]['name'])) {
                $img2_url = Service_Attach::getInstance()->uploadOSS('img2','wx/picwx','jpg');
                $goods['img2'] = $img2_url;
            }


            foreach($_FILES['img1']['name'] as $k => $v){
                if($v){
                    $_FILES["img1_{$k}"]['name'] = $v;
                    $_FILES["img1_{$k}"]['type'] = $_FILES['img1']['type'][$k];
                    $_FILES["img1_{$k}"]['type'] = $_FILES['img1']['type'][$k];
                    $_FILES["img1_{$k}"]['tmp_name'] = $_FILES['img1']['tmp_name'][$k];
                    $_FILES["img1_{$k}"]['error'] = $_FILES['img1']['error'][$k];
                    $_FILES["img1_{$k}"]['size'] = $_FILES['img1']['size'][$k];
                    $img1 = $img1 . "," . Service_Attach::getInstance()->uploadOSS("img1_{$k}",'wx/picwx','jpg');
                }
            }
            $img1 = substr($img1, 1);
            $goods['img1'] = $img1;



            //推荐大图
            if (!empty($_FILES["img3"]['name'])) {
                $img2_url = Service_Attach::getInstance()->uploadOSS('img3','wx/picwx','jpg');
                $goods['img3'] = $img2_url;
            }

            $goodsT = new FTable('goods','','xhs_master');
            $gid = $goodsT->insert($goods);
            for($i=0,$len=count($_price_old);$i<$len;$i++){
                $productT = new FTable('product','','xhs_master');
                $spec_list = '';
                if(!empty($_spec_list[$i])){
                    $spec_list = json_encode($_spec_list[$i],JSON_UNESCAPED_UNICODE);
                }
                $productT->insert(array(
                    'gid' => $gid,
                    'spec_list' => $spec_list,
                    'num' => $_num[$i]?$_num[$i]:0,
                    'price_old' => $_price_old[$i],
                    'price_new' => $_price_new[$i],
                    'purchase_price' => $_purchase_price[$i]?$_purchase_price[$i]:0,
                    'profit' => $_profit[$i]?$_profit[$i]:0,
                    'weight' => $_weight[$i]?$_weight[$i]:0,
                    'is_default' => $i == $_default ? 1 : 0
                ));
            }

            Service_Goods::clearGoodsListCache(1);
            Service_Goods::clearGoodsListCache(2);
            Service_Goods::clearCategoriesGoodsListCache();
            $this->assign('unitList',$this->getUnitList());
            $this->success('添加成功','/goods/list');
        }
        //$this->openDebug();
        $cateTable = new FTable("goods_category", '', $this->DB_SERVER);
        $cateList = $cateTable->select();
        $this->assign("goodsectionList", $cateList);
        $this->assign('unitList',$this->getUnitList());
        $this->display('goods/add');
    }

    public function saveAction(){
        global $_F;
//        $this->openDebug();
        $id = FRequest::getRequestInt('id');
        if($this->isPost()){
//            var_dump($_FILES);exit();
            $title = FRequest::getPostString('title'); //标题
            $resume = FRequest::getPostString('resume'); //简述
            $status = FRequest::getPostInt('status'); //状态
            $_product_id = $_POST['_product_id']; //属性产品ID列表
            $_spec_list = $_POST['_spec_list']; //属性列表
            $_num = $_POST['_num']; //库存
            $_price_old = $_POST['_price_old']; //原价
            $_price_new = $_POST['_price_new']; //现价
            $_purchase_price = $_POST['_purchase_price']; //成本价
            $_profit = $_POST['_profit']; //利润
            $_weight = $_POST['_weight']; //重量
            $_default = intval($_POST['_default']); //默认
            $unit = $_POST['unit']; //单位
            $details = $_POST['details']; //详情
            $mid = $_F['uid']; //管理员ID

            $freight = FRequest::getPostString('freight');
            $img2 = FRequest::getPostString('img2_txt');
            $img3 = FRequest::getPostString('img3_txt');
            $cs_num = FRequest::getPostInt('cs_num');
            $paynum = FRequest::getPostInt('paynum');
            $is_banner = FRequest::getPostInt('is_banner');
            $goodsection = FRequest::getPostInt('goodsection');
            $brand = FRequest::getPostString('brand');
            $lefttext = FRequest::getPostString('lefttext');
            $place_of_production = FRequest::getPostString('place_of_production');
            $quality_guarantee_period = FRequest::getPostString('quality_guarantee_period');
            $component = FRequest::getPostString('component');
            $paixu = FRequest::getPostInt('paixu');
            $re_degree = FRequest::getPostInt('re_degree');

            $goods = array(
                'title' => $title,
                'mid' => $mid,
                'img2' => $img2,
                'img3' => $img3,
                'resume' => $resume,
                'status' => $status,
                'unit' => $unit,
                'purchase_price' => $_purchase_price[$_default],
                'price_old' => $_price_old[$_default],
                'price_new' => $_price_new[$_default],
                'profit' => $_profit[$_default],
                'weight' => $_weight[$_default],
                'num' => array_sum($_num),
                'details' => $details,
                'create_time' => date('Y-m-d H:i:s'),
                'freight' => $freight,
                'cs_num' => $cs_num,
                'paynum' => $paynum,
                'is_banner' => $is_banner,
                'goodsection' => $goodsection,
                'brand' => $brand,
                'lefttext' => $lefttext,
                'place_of_production' => $place_of_production,
                'quality_guarantee_period' => $quality_guarantee_period,
                'component' => $component,
                'paixu' => $paixu,
                're_degree' => $re_degree,
            );

            //封面图片
            if (!empty($_FILES["img2"]['name'])) {
                $img2_url = Service_Attach::getInstance()->uploadOSS('img2','wx/picwx','jpg');
                $goods['img2'] = $img2_url;
            }

            //列表图片
            $img1 = "";
            for($i=0 ; $i<4; $i++){
                if (!empty($_FILES["img1_{$i}"]['name'])) {
                    $url = Service_Attach::getInstance()->uploadOSS("img1_{$i}",'wx/picwx','jpg');
                    $img1 = $img1 . "," . $url;
                }else{
                    if($_POST["img1_{$i}_txt"]){
                        $img1 = $img1 . "," . $_POST["img1_{$i}_txt"];
                    }
                }
            }
            $img1 = substr($img1, 1);
            $goods['img1'] = $img1;




            //首页推荐图片
            if (!empty($_FILES["img3"]['name'])) {
                $img2_url = Service_Attach::getInstance()->uploadOSS('img3','wx/picwx','jpg');
                $goods['img3'] = $img2_url;
            }

//                        var_dump($goods);exit();

            $goodsT = new FTable('goods','','xhs_master');
            $goodsT->where(array('auto_id'=>$id))->update1($goods);

            $whereStr = '';
            if(!empty($_product_id)){
                $idStr = join(',',$_product_id);
                $whereStr = "AND pid NOT IN($idStr)";
            }
            FDB::query("UPDATE product SET pstatus=-1 WHERE gid=$id $whereStr",'xhs_master');
            if(empty($_product_id)){
                for($i=0,$len=count($_price_old);$i<$len;$i++){
                    $productT = new FTable('product','','xhs_master');
                    $spec_list = '';
                    if(!empty($_spec_list[$i])){
                        $spec_list = json_encode($_spec_list[$i],JSON_UNESCAPED_UNICODE);
                    }
                    $productT->insert(array(
                        'gid' => $id,
                        'spec_list' => $spec_list,
                        'num' => $_num[$i],
                        'price_old' => $_price_old[$i],
                        'price_new' => $_price_new[$i],
                        'purchase_price' => $_purchase_price[$i]?$_purchase_price[$i]:0,
                        'profit' => $_profit[$i]?$_profit[$i]:0,
                        'weight' => $_weight[$i]?$_weight[$i]:0,
                        'is_default' => $i == $_default ? 1 : 0
                    ));
                }
            }else{
                for($i=0,$len=count($_price_old);$i<$len;$i++){
                    $productT = new FTable('product','','xhs_master');
                    $spec_list = '';
                    if(!empty($_spec_list[$i])){
                        $spec_list = json_encode($_spec_list[$i],JSON_UNESCAPED_UNICODE);
                    }
                    $productT->where(array('pid'=>$_product_id[$i]))->update1(array(
                        'gid' => $id,
                        'spec_list' => $spec_list,
                        'num' => $_num[$i],
                        'price_old' => $_price_old[$i],
                        'price_new' => $_price_new[$i],
                        'purchase_price' => $_purchase_price[$i]?$_purchase_price[$i]:0,
                        'profit' => $_profit[$i]?$_profit[$i]:0,
                        'weight' => $_weight[$i]?$_weight[$i]:0,
                        'is_default' => $i == $_default ? 1 : 0
                    ));
                }
            }
            Service_Goods::clearGoodsListCache(1);
            Service_Goods::clearGoodsListCache(2);
            Service_Goods::clearGoodsCache($id);
            Service_Goods::clearCategoriesGoodsListCache();
            $this->success('更新成功', $_F['refer']);
        }
        $goodsT = new FTable('goods','',$this->DB_SERVER);
        $goods = $goodsT->where(array('auto_id'=>$id))->find();
        $productT = new FTable('product','',$this->DB_SERVER);
        $products = $productT->where(array('gid'=>$id,'pstatus'=>1))->select();
        $this->assign('goods',$goods);
        $this->assign('products',$products);
        $this->assign('product',current($products));
        $this->assign('unitList',$this->getUnitList());
        $this->assign('id',$id);

        $cateTable = new FTable("goods_category", '', $this->DB_SERVER);
        $cateList = $cateTable->select();
        $this->assign("goodsectionList", $cateList);

        $this->display('goods/save');
    }

    public function specSetAction(){
        $this->openDebug();
        $this->display('goods/spec/set');
    }

    public function specSelectAction(){
        $this->openDebug();
        $has_id = $_REQUEST['has_id'];
        if (!empty($has_id)) {
            if(is_array($has_id)) $has_id = implode(',', $has_id);
            $whereStr = "where id not in($has_id)";
        }
        $specs = FDB::fetch("SELECT * FROM spec {$whereStr}",$this->DB_SERVER);
        $this->assign('specs', $specs);
        $this->display('goods/spec/select');
    }

    public function specAddAction(){
        $this->display('goods/spec/add');
    }

    public function specEditAction(){
        $this->openDebug();
        $id = FRequest::getRequestInt('id');
        $specT = new FTable('spec','',$this->DB_SERVER);
        $spec = $specT->where(array('id'=>$id))->find();
        $this->assign('spec', $spec);
        $this->display('goods/spec/edit');
    }



    public  function  categoryListAction(){
        global $_F;
        $id = FRequest::getInt("id");
        $where = array();
        if($id){
            $where['id']=$id;
        }
        $table = new FTable("goods_category", '', $this->DB_SERVER);
        $list = $table->where($where)->order("paixu desc")->select();
        $this->assign('data', $list);
        $this->assign("oss_url", FConfig::get("global.s_url_oss")."/uploads/");
        $this->display('goods/category-list');
    }

    /*
     * 添加产品系列
     */
    public function categoryModifyAction(){
        global $_F;
        $id = FRequest::getInt("id");
        if($this->isPost()){
            $id = FRequest::getPostInt('id');
            $paixu = FRequest::getPostInt('paixu');
            $name = FRequest::getPostString("name");

            $save = array();
            //图标
            if (!empty($_FILES["icon"]['name'])) {
                $img2_url = Service_Attach::getInstance()->uploadOSS('icon','xhs/goods','jpg');
                $save['icon'] = $img2_url;
            }
            if($name){
                $save['name'] = $name;
            }
            if($paixu){
                $save['paixu'] = $paixu;
            }

            $table = new FTable("goods_category", "", 'xhs_master');
            if($id){
                $table->update1($save, array("id" => $id));
                $this->success("修改成功", $_F['uri'] . "?id=" . $id);
            }else{
                $ret = $table->insert($save);
                if($ret){
                    $this->success("添加成功", "/goods/categoryList");
                }else{
                    $this->error("添加失败", $_F['refer']);
                }
            }

        }else{
            $table =  new FTable("goods_category", "", $this->DB_SERVER);
            $data = $table->fields("*")->where(array("id" => $id))->find();
            $this->assign("data", $data);
        }
        $this->assign("oss_url", FConfig::get("global.s_url_oss")."/uploads/");
        $this->display("goods/category-modify");
    }

    /*
     * 删除产品系列
     */
    public function categoryDelAction(){

        global $_F;
        $id = FRequest::getInt('id') ? FRequest::getInt('id') : 0;
        if($id){
            $table = new FTable("goods_category", "", 'xhs_master');
            $table->where("id={$id}")->remove(true);
            Service_Goods::clearCategoriesGoodsListCache();
            $this->success('删除分类成功', $_F['refer']);

        }else{
            $this->error('id参数为空', $_F['refer']);
        }


    }


    public function delAction(){
        global $_F;
        $id = FRequest::getInt("id");
        if($id){
            $table = new FTable("goods", "", 'xhs_master');
            $table->update1(array('status' => -1), array("auto_id" => $id));
            $this->success("删除成功", $_F['refer']);
        }else{
            $this->error('id为空', $_F['refer']);
        }
    }

    /*
     *产品列表
     */
    public function goodsListAction(){
        global $_F;

        $this->openDebug();
        $title = FRequest::getString('title');
//        $start_time = FRequest::getString("begin_date");
//        $end_time = FRequest::getString('end_date');
        $page = FRequest::getInt("page");
        $is_banner = FRequest::getInt("is_banner");
        $goodsection = FRequest::getInt("goodsection");
        $is_soldout = FRequest::getInt("is_soldout");
        $status = FRequest::getInt("status");


        $where = array();

        /*if ($start_time < 1) {
            $start_time = date('Y-m-d', time());
        }
        if ($end_time < 1) {
            $end_time = date('Y-m-d', time());
        }
        $where['create_time']['gte'] = $start_time.' 00:00:00';
        $where['create_time']['lte'] = $end_time.' 23:59:59';*/


        if($title){
            $where['title'] = array('like' => "%{$title}%");
        }
        if($is_banner){
            $where['is_banner'] =$is_banner;
        }
        if($goodsection){
            $where['goodsection'] =$goodsection;
        }
        if($is_soldout){
            $where['is_soldout'] = $is_soldout;
        }
        if($status){
            $where['status'] = $status;
        }

        $table = new FTable("goods", "", $this->DB_SERVER);

        $list = $table->fields("*")
            ->where($where)
            ->order("paixu desc")
            ->limit(20)
            ->page($page)
            ->select();
        $pagerInfo = $table->getPagerInfo();
        $this->assign('page_info', $pagerInfo);
        $this->assign("data", $list);

        $cateTable = new FTable("goods_category", '', $this->DB_SERVER);
        $cateList = $cateTable->select();
        $this->assign("goodsectionList", $cateList);
        $this->display("goods/goods-list");
    }

    private function getUnitList(){
        return array(
            '份','袋','盒','个','杯','瓶','根',
        );
    }

    /*
     * 产品列表
     */
    public function productListAction(){
        global $_F;

        $this->openDebug();
        $gid = FRequest::getInt("gid");
        $title = FRequest::getString("title");
        $page = FRequest::getInt("page");
        $where = array();
        if($gid){
            $where['p.gid'] = $gid;
        }
        if($title){
            $where['g.title'] = array("like" => "%{$title}%");
        }

        $proTable = new FTable("product", "p", $this->DB_SERVER);
        $list = $proTable->fields("p.*, g.title as title")
            ->leftJoin("goods", 'g', "p.gid=g.auto_id")
            ->where($where)
            ->order("p.pid desc")
            ->limit(20)
            ->page($page)
            ->select();

        $pagerInfo = $proTable->getPagerInfo();
        $this->assign('page_info', $pagerInfo);

        $this->assign("data", $list);
        $this->display('goods/product-list');
    }


    public function menuAction(){
        require_once(APP_ROOT . 'lib/weixin/WeixinChat.class.php');
        $options = array(
            'token' => FConfig::get('wechat.token'),
            'appid' => FConfig::get('wechat.appid'),
            'appsecret' => FConfig::get('wechat.appsecret'),
        );
        $weixin = new WeixinChat($options);
        $weixin->checkAuth();
        $menuList = array(
            'button' =>
                array(
                    'name' => '关于',
                    'sub_button' => array(
                        array(
                            'type' => 'view',
                            'name' => '配送范围',
                            'url' => 'http://order.xhs1985.com/store/range',
                        ),
                        array(
                            'type' => 'view',
                            'name' => '门店地址',
                            'url' => 'http://order.xhs1985.com/store/list',
                        ),
                    ),
                ),
                array(
                    'type' => 'view',
                    'name' => '点外卖',
                    'url' => 'http://order.xhs1985.com',
                ),
                array(
                    'type' => 'view',
                    'name' => '我的订单',
                    'url' => 'http://order.xhs1985.com/user/index',
                ),
        );
        /*$menuList = array(
            'button' =>
                array(
                    'type' => 'click',
                    'name' => '领取福利',
                    'key' => 'DRAW_WEAL',
                )
        );*/
        var_dump($weixin->createMenu(array('button'=>array_values($menuList))));
    }

    public function menu1Action(){
        require_once(APP_ROOT . 'lib/weixin/WeixinChat.class.php');
        $options = array(
            'token' => FConfig::get('wechat.seller.token'),
            'appid' => FConfig::get('wechat.seller.appid'),
            'appsecret' => FConfig::get('wechat.seller.appsecret'),
        );
        $weixin = new WeixinChat($options);
        $weixin->checkAuth();
        $menuList = array(
            'button' =>
                array(
                    'type' => 'view',
                    'name' => '待接单',
                    'url' => FConfig::get('global.burl') . '/order/manager',
                ),
                array(
                    'type' => 'view',
                    'name' => '我的',
                    'url' => FConfig::get('global.burl') . '/user/myCenter',
                ),
        );
        return $weixin->createMenu(array('button'=>array_values($menuList)));
    }

    /*public function testAction(){
        $data = array(
            array(
                'title' => '一只小红薯',
                'description' => '好吃',
                'url' => 'http://order.xhs1985.com',
                'picurl' => 'http://p9.pstatp.com/list/190x124/37c80001b89a997f1e15',
            )
        );
        require_once(APP_ROOT . 'lib/weixin/WeixinChat.class.php');
        $options = array(
            'token' => FConfig::get('wechat.token'),
            'appid' => FConfig::get('wechat.appid'),
            'appsecret' => FConfig::get('wechat.appsecret'),
        );
        $wechat = new WeixinChat($options);
        $wechat->sendCustomMessage('oQBIz1AMNlrzkAOUq0qado6_u9SU',$data,'news');
        $wechat->sendCustomMessage('oQBIz1GyziL_rLQl8QPuCYP3Z2Xc',$data,'news');
    }*/

    public function goodsUrlAction(){
        $id=FRequest::getInt('id');
        $this->assign('id', $id);
        $this->display('goods/goods-url');

    }

    /**
     * 修改商品分类
     */
    public function goodsCategoryModifyAction(){
        global $_F;
        if($this->isPost()){
            $id = FRequest::getPostInt('id');
            $goodsection = FRequest::getPostInt('goodsection');
            if(!$id || !$goodsection){
                $this->error('参数不对', $_F['refer']);
            }
            $save = array('goodsection' => $goodsection);
            $table = new FTable('goods', '', $this->DB_SERVER_MASTER);
            $ret = $table->where(array('auto_id' => $id))->save($save);
            if($ret){
                $this->success('分类修改成功', $_F['refer']);
            }else{
                $this->error('分类修改失败', $_F['refer']);
            }

            Service_Goods::clearCategoriesGoodsListCache();
        }

        $id = FRequest::getInt('id');
        if($id){
            $table = new FTable('goods', '', $this->DB_SERVER);
            $data = $table->fields('auto_id, goodsection')->where(array('auto_id' => $id))->find();
            $this->assign('data', $data);
        }

        $cateTable = new FTable('goods_category', '', $this->DB_SERVER);
        $cateList = $cateTable->select();
        $this->assign("goodsectionList", $cateList);

        $this->display('goods/goods-category-modify');
    }

    /**
     * 商品销量统计
     */
    public function goodsTjAction(){
        global $_F;
//        $this->openDebug();
//        $page = FRequest::getInt("page");
        $start_time = FRequest::getString("begin_date");
        $end_time = FRequest::getString('end_date');

        $where = array();

        if ($start_time < 1) {
            $start_time = date('Y-m-d', strtotime("-6 days"));
        }
        $this->assign('begin_date', $start_time);
        if ($end_time < 1) {
            $end_time = date('Y-m-d', time());
        }
        $this->assign('end_date', $end_time);
        $where['o.create_time']['gte'] = $start_time.' 00:00:00';
        $where['o.create_time']['lte'] = $end_time.' 23:59:59';


        $where['o.status'] = 5;

        $userTable = new FTable("orders_product", 'op', $this->DB_SERVER);
        $list = $userTable->fields("op.gid, COUNT(*) as c,sum(op.paynum) as paynum_sum")
            ->leftJoin('orders', 'o', 'o.o_id=op.o_id')
            ->where($where)
            ->group(array('op.gid'))
            ->select();
        $list = self::my_sort($list, 'paynum_sum', SORT_DESC);
        $proTable = new FTable('orders_product', '', $this->DB_SERVER);
        foreach($list as &$item){
            $ret = $proTable->fields('title, price_new, profit, purchase_price, spec_list')->where("gid={$item['gid']}")->order("id desc")->find();
            $item['goods_detail'] = $ret;
        }

//        FResponse::output($list);
//        exit();

        $this->assign("data", $list);
        $this->display('goods/goods-tj');
    }

    /**
     * 商品销量导出
     */
    public function excelGoodsAction(){
        global $_F;
        $this->openDebug();
//        $page = FRequest::getInt("page");
        $start_time = FRequest::getString("begin_date");
        $end_time = FRequest::getString('end_date');

        $where = array();

        if ($start_time < 1) {
            $start_time = date('Y-m-d', strtotime("-6 days"));
        }
        if ($end_time < 1) {
            $end_time = date('Y-m-d', time());
        }
        $where['o.create_time']['gte'] = $start_time.' 00:00:00';
        $where['o.create_time']['lte'] = $end_time.' 23:59:59';


        $where['o.status'] = 5;

        $userTable = new FTable("orders_product", 'op', $this->DB_SERVER);
        $list = $userTable->fields("op.gid, COUNT(*) as c,sum(op.paynum) as paynum_sum")
            ->leftJoin('orders', 'o', 'o.o_id=op.o_id')
            ->where($where)
            ->group(array('op.gid'))
            ->select();
//        array_multisort($list, 'paynum_sum');
        $list = self::my_sort($list, 'paynum_sum', SORT_DESC);
        $proTable = new FTable('orders_product', '', $this->DB_SERVER);
        foreach($list as &$item){
            $ret = $proTable->fields('title, price_new, profit, purchase_price, spec_list')->where("gid={$item['gid']}")->order("id desc")->find();
            $item['goods_detail'] = $ret;
        }

        //日期	产品名称	商品规格	商品销售数量	商品单价	销售总金额	商品单成本	商品单利润	商品总利润
        $data = array();
        $data[0] = array("日期", "产品名称", "商品规格", "商品销售数量", "商品单价",
            "销售总金额", "商品单成本", "商品单利润", "商品总利润");

        foreach ($list as $k => $o) {
            $data[$k + 1][0] = "{$start_time}~{$end_time}";
            $data[$k + 1][1] = $o['goods_detail']['title'];
            $tmp = json_decode($o['goods_detail']['spec_list'], true);
            $new = "";
            foreach($tmp as $k1 => $v1){
                $new = json_decode($v1);
            }
            $data[$k + 1][2] = $new->value;
            $data[$k + 1][3] = $o['paynum_sum'];
            $data[$k + 1][4] = $o['goods_detail']['price_new'];
            $data[$k + 1][5] = $o['goods_detail']['price_new']*$o['paynum_sum'];
            $data[$k + 1][6] = $o['goods_detail']['purchase_price'];
            $profit=$o['goods_detail']['price_new']-$o['goods_detail']['purchase_price'];
            $data[$k + 1][7] = $profit;
            $data[$k + 1][8] = $profit*$o['paynum_sum'];
        }

        $sheetName = "{$start_time}至{$end_time}";
        $fileName = iconv("utf-8", "gb2312", "{$sheetName}商品销量列表导出");
        $xls = new FExcel('UTF-8', false, $sheetName);
        $xls->addArray($data);
        $xls->generateXML($fileName);

        exit();

    }

    public static function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
        if(is_array($arrays)){
            foreach ($arrays as $array){
                if(is_array($array)){
                    $key_arrays[] = $array[$sort_key];
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
        return $arrays;
    }



}
